﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using TwinCAT.Ads;
using System.Runtime.InteropServices;
using System.Threading;
using Entity;
using DAL;
using System.Data;

namespace Project_V1
{

    
    class AlarmHanlder
    {
  
        public static bool[] alarmTmpArr = new bool[100 + 1];  //报警开始位为1

        public static string alarmNewStr = "";

        public static string[] alarmVarnameArr1 = { "_03_HMI.SysAlarmActive",
                                                    "Main_Sys.MEmgStop",
                                                    "Main_Sys.Exc_EmgStop",
                                                    "_02_InOutput.biSwEmgStop",
                                                    "_02_InOutput.biEbEmgStop",
                                                    "_03_HMI.Error1",
                                                    "_03_HMI.Error2"};   //报警

         
        public static string[] alarmVarnameArr2 = { "_03_HMI.FeedingNOK",
                                                    "_03_HMI.FeedMachBlowRivetOverTimeAlarm",
                                                    "_03_HMI.FeedMachRivetOutOverTimeAlarm",
                                                    "_03_HMI.CachePlaceRivetInOverTimeAlarm",
                                                    "_03_HMI.CachePlaceRivetAtOverTimeAlarm",
                                                    "_03_HMI.CachePlaceBlowRivetOverTimeAlarm",
                                                    "_03_HMI.CachePlaceRivetOutOverTimeAlarm",
                                                    "_03_HMI.GunHeadRivetInOverTimeAlarm",
                                                    "_03_HMI.PrePressingNOK",
                                                    "_03_HMI.PrePressingNOK_OverTime",
                                                    "_03_HMI.PrePressingNOK_NOTVacuo",
                                                    "_03_HMI.PrePressingNOK_OverPosition",
                                                    "_03_HMI.RivetingNOK",
                                                    "_03_HMI.Rivet1ingNOK",
                                                    "_03_HMI.Rivet1ingNOK_OverTime",
                                                    "_03_HMI.Rivet1ingNOK_OverSpeed",
                                                    "_03_HMI.Rivet1ingNOK_OverPosition",
                                                    "_03_HMI.Rivet2ingNOK",
                                                    "_03_HMI.Rivet2ingNOK_OverTime",
                                                    "_03_HMI.Rivet2ingNOK_OverSpeed",
                                                    "_03_HMI.Rivet2ingNOK_OverPosition",
                                                    "_03_HMI.Rivet3ingNOK",
                                                    "_03_HMI.Rivet3ingNOK_OverTime",
                                                    "_03_HMI.Rivet3ingNOK_OverSpeed",
                                                    "_03_HMI.Rivet3ingNOK_OverPosition",
                                                    "_03_HMI.LimitSwitchUp",
                                                    "_03_HMI.LimitSwitchDown"}; //警告类

         
        public static string[] alarmVarnameArr3 = { "_02_InOutput.biContactor1",
                                                    "_02_InOutput.biContactor2",
                                                    "_02_InOutput.biAxis1Ready",
                                                    "_02_InOutput.biAxis2Ready",
                                                    "_03_HMI.SysIsReady",
                                                    "_03_HMI.Enabled1",
                                                    "_03_HMI.Enabled2",
                                                    "_03_HMI.SysManualMode",
                                                    "_03_HMI.SysAutoMode",
                                                    "_03_HMI.SysExcMode",
                                                    "_03_HMI.SysDebugMode",
                                                    "_03_HMI.btMotorDebug",
                                                    "_03_HMI.btFeedTest",
                                                    "_02_InOutput.biBtRun",
                                                    "_02_InOutput.biBtReset",
                                                    "_03_HMI.VacuoValueRch1",
                                                    "_02_InOutput.biTotaInAirPresRch1",
                                                    "_02_InOutput.biTotaInAirPresRch2",
                                                    "_03_HMI.Feeding",
                                                    "_03_HMI.PrePressing",
                                                    "_03_HMI.Riveting",
                                                    "_03_HMI.FeedingStop",
                                                    "_03_HMI.PrePressingStop",
                                                    "_03_HMI.RivetingStop",
                                                    "_03_HMI.FeedingOK",
                                                    "_03_HMI.PrePressingOK",
                                                    "_03_HMI.RivetingOK",
                                                    "_03_HMI.Rivet1ing",
                                                    "_03_HMI.Rivet1ingStop",
                                                    "_03_HMI.Rivet1ingOK",
                                                    "_03_HMI.Rivet1ingOK_SpeedJudgment",
                                                    "_03_HMI.Rivet1ingOK_PositionVariationJudgment",
                                                    "_03_HMI.Rivet1ingOK_TorqueJudgment",
                                                    "_03_HMI.Rivet1ingOK_PositionJudgment",
                                                    "_03_HMI.Rivet2ing",
                                                    "_03_HMI.Rivet2ingStop",
                                                    "_03_HMI.Rivet2ingOK",
                                                    "_03_HMI.Rivet2ingOK_SpeedJudgment",
                                                    "_03_HMI.Rivet2ingOK_PositionVariationJudgment",
                                                    "_03_HMI.Rivet2ingOK_TorqueJudgment",
                                                    "_03_HMI.Rivet2ingOK_PositionJudgment",
                                                    "_03_HMI.Rivet3ing",
                                                    "_03_HMI.Rivet3ingStop",
                                                    "_03_HMI.Rivet3ingOK",
                                                    "_03_HMI.Rivet3ingOK_SpeedJudgment",
                                                    "_03_HMI.Rivet3ingOK_PositionVariationJudgment",
                                                    "_03_HMI.Rivet3ingOK_TorqueJudgment",
                                                    "_03_HMI.Rivet3ingOK_PositionJudgment"}; //提示类
         
        public static Thread alarmHanlder;
        public static string alarmStr = "";
        public static string alarmTmpStr = "";
        public static string username = "";
        public static string category = "";

        public static void AlarmThreadStart()
        {
            alarmHanlder = new Thread(alarmRun);
            alarmHanlder.IsBackground = true;
            alarmHanlder.Start();
        }


        public static string AlarmTypeName(string varname)
        {
            string res = "";

            if (varname == "_03_HMI.SysAlarmActive") { res = "系统总故障"; }
            if (varname == "Main_Sys.MEmgStop") { res = "急停总故障"; }
            if (varname == "Main_Sys.Exc_EmgStop") { res = "外控设备急停故障"; }
            if (varname == "_02_InOutput.biSwEmgStop") { res = "操作面板急停故障"; }
            if (varname == "_02_InOutput.biEbEmgStop") { res = "控制电柜急停故障"; }
            if (varname == "_03_HMI.Error1") { res = "旋转轴故障"; }
            if (varname == "_03_HMI.Error2") { res = "进给轴故障"; }
 
            if (varname == "_03_HMI.FeedingNOK") { res = "送钉不成功"; }
            if (varname == "_03_HMI.FeedMachBlowRivetOverTimeAlarm") { res = "送钉不成功_送钉机吹钉超时"; }
            if (varname == "_03_HMI.FeedMachRivetOutOverTimeAlarm") { res = "送钉不成功_送钉机出钉超时"; }
            if (varname == "_03_HMI.CachePlaceRivetInOverTimeAlarm") { res = "送钉不成功_缓存处进钉超时"; }
            if (varname == "_03_HMI.CachePlaceRivetAtOverTimeAlarm") { res = "送钉不成功_缓存处铆钉到位超时"; }
            if (varname == "_03_HMI.CachePlaceBlowRivetOverTimeAlarm") { res = "送钉不成功_缓存处吹钉超时"; }
            if (varname == "_03_HMI.CachePlaceRivetOutOverTimeAlarm") { res = "送钉不成功_缓存处出钉超时"; }
            if (varname == "_03_HMI.GunHeadRivetInOverTimeAlarm") { res = "送钉不成功_枪头处进钉超时"; }
            if (varname == "_03_HMI.PrePressingNOK") { res = "预压不成功"; }
            if (varname == "_03_HMI.PrePressingNOK_OverTime") { res = "预压不成功_超时"; }
            if (varname == "_03_HMI.PrePressingNOK_NOTVacuo") { res = "预压不成功_掉真空"; }
            if (varname == "_03_HMI.PrePressingNOK_OverPosition") { res = "预压不成功_超限"; }
            if (varname == "_03_HMI.RivetingNOK") { res = "铆接不成功"; }
            if (varname == "_03_HMI.Rivet1ingNOK") { res = "第1段铆接不成功"; }
            if (varname == "_03_HMI.Rivet1ingNOK_OverTime") { res = "第1段铆接不成功_超时"; }
            if (varname == "_03_HMI.Rivet1ingNOK_OverSpeed") { res = "第1段铆接不成功_超速"; }
            if (varname == "_03_HMI.Rivet1ingNOK_OverPosition") { res = "第1段铆接不成功_超限"; }
            if (varname == "_03_HMI.Rivet2ingNOK") { res = "第2段铆接不成功"; }
            if (varname == "_03_HMI.Rivet2ingNOK_OverTime") { res = "第2段铆接不成功_超时"; }
            if (varname == "_03_HMI.Rivet2ingNOK_OverSpeed") { res = "第2段铆接不成功_超速"; }
            if (varname == "_03_HMI.Rivet2ingNOK_OverPosition") { res = "第2段铆接不成功_超限"; }
            if (varname == "_03_HMI.Rivet3ingNOK") { res = "第3段铆接不成功"; }
            if (varname == "_03_HMI.Rivet3ingNOK_OverTime") { res = "第3段铆接不成功_超时"; }
            if (varname == "_03_HMI.Rivet3ingNOK_OverSpeed") { res = "第3段铆接不成功_超速"; }
            if (varname == "_03_HMI.Rivet3ingNOK_OverPosition") { res = "第3段铆接不成功_超限"; }
            if (varname == "_03_HMI.LimitSwitchUp") { res = "进给轴超上硬限位"; }
            if (varname == "_03_HMI.LimitSwitchDown") { res = "进给轴超下硬限位"; }
        
            if (varname == "_02_InOutput.biContactor1") { res = "旋转轴已上电"; }
            if (varname == "_02_InOutput.biContactor2") { res = "进给轴已上电"; }
            if (varname == "_02_InOutput.biAxis1Ready") { res = "旋转轴已准备就绪"; }
            if (varname == "_02_InOutput.biAxis2Ready") { res = "进给轴已准备就绪"; }
            if (varname == "_03_HMI.SysIsReady") { res = "系统已准备就绪"; }
            if (varname == "_03_HMI.Enabled1") { res = "旋转轴已使能"; }
            if (varname == "_03_HMI.Enabled2") { res = "进给轴已使能"; }
            if (varname == "_03_HMI.SysManualMode") { res = "手动模式中"; }
            if (varname == "_03_HMI.SysAutoMode") { res = "自动模式中"; }
            if (varname == "_03_HMI.SysExcMode") { res = "外控模式中"; }
            if (varname == "_03_HMI.SysDebugMode") { res = "调试模式中"; }
            if (varname == "_03_HMI.btMotorDebug") { res = "电机调试中"; }
            if (varname == "_03_HMI.btFeedTest") { res = "送钉测试中"; }
            if (varname == "_02_InOutput.biBtRun") { res = "启动按钮已按下"; }
            if (varname == "_02_InOutput.biBtReset") { res = "复位按钮已按下"; }
            if (varname == "_03_HMI.VacuoValueRch1") { res = "真空压力已达到"; }
            if (varname == "_02_InOutput.biTotaInAirPresRch1") { res = "1#数字口总进气压力已达到"; }
            if (varname == "_02_InOutput.biTotaInAirPresRch2") { res = "2#数字口总进气压力已达到"; }
            if (varname == "_03_HMI.Feeding") { res = "送钉进行中"; }
            if (varname == "_03_HMI.PrePressing") { res = "预压进行中"; }
            if (varname == "_03_HMI.Riveting") { res = "铆接进行中"; }
            if (varname == "_03_HMI.FeedingStop") { res = "送钉停止中"; }
            if (varname == "_03_HMI.PrePressingStop") { res = "预压停止中"; }
            if (varname == "_03_HMI.RivetingStop") { res = "铆接停止中"; }
            if (varname == "_03_HMI.FeedingOK") { res = "送钉成功"; }
            if (varname == "_03_HMI.PrePressingOK") { res = "预压成功"; }
            if (varname == "_03_HMI.RivetingOK") { res = "铆接成功"; }
            if (varname == "_03_HMI.Rivet1ing") { res = "第1段铆接进行中"; }
            if (varname == "_03_HMI.Rivet1ingStop") { res = "第1段铆接停止中"; }
            if (varname == "_03_HMI.Rivet1ingOK") { res = "第1段铆接成功"; }
            if (varname == "_03_HMI.Rivet1ingOK_SpeedJudgment") { res = "第1段铆接成功_速度判断"; }
            if (varname == "_03_HMI.Rivet1ingOK_PositionVariationJudgment") { res = "第1段铆接成功_位置变化量判断"; }
            if (varname == "_03_HMI.Rivet1ingOK_TorqueJudgment") { res = "第1段铆接成功_扭矩判断"; }
            if (varname == "_03_HMI.Rivet1ingOK_PositionJudgment") { res = "第1段铆接成功_位置判断"; }
            if (varname == "_03_HMI.Rivet2ing") { res = "第2段铆接进行中"; }
            if (varname == "_03_HMI.Rivet2ingStop") { res = "第2段铆接停止中"; }
            if (varname == "_03_HMI.Rivet2ingOK") { res = "第2段铆接成功"; }
            if (varname == "_03_HMI.Rivet2ingOK_SpeedJudgment") { res = "第2段铆接成功_速度判断"; }
            if (varname == "_03_HMI.Rivet2ingOK_PositionVariationJudgment") { res = "第2段铆接成功_位置变化量判断"; }
            if (varname == "_03_HMI.Rivet2ingOK_TorqueJudgment") { res = "第2段铆接成功_扭矩判断"; }
            if (varname == "_03_HMI.Rivet2ingOK_PositionJudgment") { res = "第2段铆接成功_位置判断"; }
            if (varname == "_03_HMI.Rivet3ing") { res = "第3段铆接进行中"; }
            if (varname == "_03_HMI.Rivet3ingStop") { res = "第3段铆接停止中"; }
            if (varname == "_03_HMI.Rivet3ingOK") { res = "第3段铆接成功"; }
            if (varname == "_03_HMI.Rivet3ingOK_SpeedJudgment") { res = "第3段铆接成功_速度判断"; }
            if (varname == "_03_HMI.Rivet3ingOK_PositionVariationJudgment") { res = "第3段铆接成功_位置变化量判断"; }
            if (varname == "_03_HMI.Rivet3ingOK_TorqueJudgment") { res = "第3段铆接成功_扭矩判断"; }
            if (varname == "_03_HMI.Rivet3ingOK_PositionJudgment") { res = "第3段铆接成功_位置判断"; }

            return res;

        }


            #region 新增报警
            /// <summary>
            /// 添加紧固件对象信息到数据库
            /// </summary>
            /// <param name="objFastener"></param>
            /// <returns></returns>
        public static int AddAlarmData(AlarmData objAlarmData)
        {

            StringBuilder objBuilder = new StringBuilder();

            objBuilder.Append("insert into AlarmData(InsertTime,VarName,AlarmState,Priority,AlarmType,Value,AlarmValue,Operator,category)");
            objBuilder.Append(" values(   cast( '{0}' as datetime) ,'{2}','{3}','{4}',N'{5}','{6}','{7}','"+ AlarmHanlder.username + "',N'{9}')");

            //objBuilder.Append("insert into AlarmData(InsertTime,EndTime,VarName,AlarmState,Priority,AlarmType,Value,AlarmValue,Operator)");
            //objBuilder.Append(" values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}')");

            string sql = string.Format(objBuilder.ToString(),
                objAlarmData.InsertTime, objAlarmData.EndTime,  objAlarmData.VarName,
                objAlarmData.AlarmState, objAlarmData.Priority, AlarmTypeName(objAlarmData.VarName), objAlarmData.Value, objAlarmData.AlarmValue, objAlarmData.Operator,objAlarmData.Category);

            //提交到数据库
            try
            {
                return SQLHelper.Update(sql);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 更新紧固件,不可更改编号
        /// <summary>
        /// 更新紧固件信息到数据库
        /// </summary>
        /// <param name="objFastener"></param>
        /// <returns></returns>
        public static int ModifyAlarmData(AlarmData objAlarmData,string varnname)
        {

            StringBuilder objBuilder = new StringBuilder();
            //InsertTime,EndTime,VarName,AlarmState,Priority,AlarmType,Value,AlarmValue,Operator  cast('YYYY-MM-DD   HH24:MI:SS'   as   datetime)
            objBuilder.Append("Update AlarmData set EndTime= cast('{1}' as   datetime),AlarmState='{3}',Priority='{4}' ,Value='{6}',AlarmValue='{7}',Operator='" + AlarmHanlder.username + "',category = N'{9}'");
            objBuilder.Append(" where EndTime is null and VarName = '" + varnname + "' and Value = 'True'" );
            string sql = string.Format(objBuilder.ToString(),
                objAlarmData.InsertTime, objAlarmData.EndTime, AlarmTypeName(objAlarmData.VarName),
                objAlarmData.AlarmState, objAlarmData.Priority, AlarmTypeName(objAlarmData.VarName),
                objAlarmData.Value, objAlarmData.AlarmValue, objAlarmData.Operator, objAlarmData.Category);
            //提交到数据库
            try
            {
                return SQLHelper.Update(sql);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion


        public static void alarmRun()
        {
            while (true)
            {
                try
                {
                    alarmStr = "";
                    for (int i = 0; i <= alarmVarnameArr1.Length; i++)
                    { 
                         
                        try
                        {
                            string tmp = CommonMethods.CurrentValue[alarmVarnameArr1[i]].ToString();
                            AlarmData objAlarmData = new AlarmData()
                                {
                                    InsertTime = System.DateTime.Now,
                                    EndTime = System.DateTime.Now,
                                    VarName = alarmVarnameArr1[i],
                                    AlarmState = "",
                                    Priority = "",
                                    AlarmType = "",
                                    Value = tmp,
                                    AlarmValue = tmp,
                                    Operator = "",
                                    Category = "故障类"
                                };


                            if (alarmVarnameArr1[i] != "_02_InOutput.biSwEmgStop" || alarmVarnameArr1[i] != "_02_InOutput.biEbEmgStop")
                            {
                                int bak = 0;
                            }
                         



                                //tmp = "True";
                                if (tmp == "True")//报警插入
                                {
                                    try
                                    {
                                        string sqlstr = "select * from AlarmData where VarName = '" + alarmVarnameArr1[i] + "'  and Value = 'True'";
                                        if (SQLHelper.GetDataSet(sqlstr).Tables[0].Rows.Count == 0)
                                        {

                                            AddAlarmData(objAlarmData);
                                        }
                                    }
                                    catch
                                    {
                                    }
                                    alarmStr += alarmTmpArr[i];
                                }

                                if (tmp == "False")//停止报警更新
                                {
                                    try
                                    {
                                        string sqlstr = "select * from AlarmData where VarName = '" + alarmVarnameArr1[i] + "'  and Value = 'True'";
                                        if (SQLHelper.GetDataSet(sqlstr).Tables[0].Rows.Count > 0)
                                        {
                                            ModifyAlarmData(objAlarmData, alarmVarnameArr1[i]);
                                        }
                                    }
                                    catch(Exception ex)
                                    {
                                    int baa = 0;
                                    }
                                }
                          
                             



 







                            }
                            catch (Exception ex)
                            {
                            } 
                    }


 
                    for (int i = 0; i <= alarmVarnameArr2.Length; i++)
                    { 
                     
                        try
                        {
                            string tmp = CommonMethods.CurrentValue[alarmVarnameArr2[i]].ToString();
                            AlarmData objAlarmData = new AlarmData()
                            {
                                InsertTime = System.DateTime.Now,
                                EndTime = System.DateTime.Now,
                                VarName = alarmVarnameArr2[i],
                                AlarmState = "",
                                Priority = "",
                                AlarmType = "",
                                Value = tmp,
                                AlarmValue = tmp,
                                Operator = "",
                                Category = "警告类"
                            };

                            if (tmp == "True")//报警插入
                            {
                                try
                                {
                                    string sqlstr = "select * from AlarmData where VarName = '" + alarmVarnameArr2[i] + "'  and Value = 'True'";
                                    if (SQLHelper.GetDataSet(sqlstr).Tables[0].Rows.Count == 0)
                                    {
                                        AddAlarmData(objAlarmData);
                                    }
                                }
                                catch
                                {
                                }
                                alarmStr += alarmTmpArr[i];
                            }

                            if (tmp == "False")//停止报警更新
                            {
                                try
                                {
                                    string sqlstr = "select * from AlarmData where VarName = '" + alarmVarnameArr2[i] + "'  and Value = 'True'";
                                    if (SQLHelper.GetDataSet(sqlstr).Tables[0].Rows.Count > 0)
                                    {
                                        ModifyAlarmData(objAlarmData, alarmVarnameArr2[i]);
                                    }
                                }
                                catch
                                {
                                }
                            } 




                        }
                        catch (Exception ex)
                        {
                        } 
                    }


 
                    for (int i = 0; i <= alarmVarnameArr3.Length; i++)
                    { 
                  
                        try
                        {
                            string tmp = CommonMethods.CurrentValue[alarmVarnameArr3[i]].ToString();
                            AlarmData objAlarmData = new AlarmData()
                            {
                                InsertTime = System.DateTime.Now,
                                EndTime = System.DateTime.Now,
                                VarName = alarmVarnameArr3[i],
                                AlarmState = "",
                                Priority = "",
                                AlarmType = "",
                                Value = tmp,
                                AlarmValue = tmp,
                                Operator = "",
                                Category = "提示类"
                            };

                    

                                if (tmp == "True")//报警插入
                                {
                                    try
                                    {
                                        string sqlstr = "select * from AlarmData where VarName = '" + alarmVarnameArr3[i] + "'  and Value = 'True'";
                                        if (SQLHelper.GetDataSet(sqlstr).Tables[0].Rows.Count == 0)
                                        {
                                            AddAlarmData(objAlarmData);
                                        }
                                    }
                                    catch
                                    {
                                    }
                                    alarmStr += alarmTmpArr[i];
                                }

                                if (tmp == "False")//停止报警更新
                                {
                                    try
                                    {
                                        string sqlstr = "select * from AlarmData where VarName = '" + alarmVarnameArr3[i] + "'  and Value = 'True'";
                                        if (SQLHelper.GetDataSet(sqlstr).Tables[0].Rows.Count > 0)
                                        {
                                            ModifyAlarmData(objAlarmData, alarmVarnameArr3[i]);
                                        }
                                    }
                                    catch
                                    {
                                    }
                                }
                            

                           





                        }
                        catch (Exception ex)
                        {
                        } 
                    }

                }
                catch(Exception ex)
                {
                }


      

                try
                {
                    DataSet AlarmDS = new DataSet();
                    string sqlstr = "select * from AlarmData where endTime <> '' and endTime is not null order by insertTIME desc ";
                    AlarmDS = SQLHelper.GetDataSet(sqlstr);
                    alarmNewStr = AlarmDS.Tables[0].Rows[0]["insertTIME"].ToString() + "    " + AlarmDS.Tables[0].Rows[0]["[AlarmType]"].ToString();

                }
                catch 
                {


                }

                Thread.Sleep(3000);
            }

 

 
        }

    }
}
